package zhao.tx.eecs.zhao;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.andware.volley.Request;
import com.andware.volley.VolleyError;
import com.andware.volley.toolbox.JsonRequest;
import com.google.gson.Gson;

import org.joda.time.DateTime;

import java.util.Date;

import zhao.tx.eecs.AbsActivity.BaseActivity;
import zhao.tx.eecs.JsonModel.LoginModel;
import zhao.tx.eecs.JsonModel.MessageModel;
import zhao.tx.eecs.JsonModel.TimeModel;
import zhao.tx.eecs.JsonModel.UserModel;
import zhao.tx.eecs.MyConstants;
import zhao.tx.eecs.R;
import zhao.tx.eecs.Tools.CookieTools;
import zhao.tx.eecs.Tools.SharedPreferencesHelper;
import zhao.tx.eecs.Tools.UserFileDeal;
import zhao.tx.eecs.Tools.VolleyBase;
import zhao.tx.eecs.Tools.VolleyCookieBase;

public class Login extends BaseActivity {

    private String struser;
    private String strpwd;
    private EditText username;
    private EditText password;

    private CheckBox checkBox;

    private Request loginRequest;

    private ProgressDialog dialog;

    private Handler handler = new Handler () {
        @Override
        public void handleMessage ( Message msg ) {
        }
    };

    @Override
    protected void onCreate ( Bundle savedInstanceState ) {
        super.onCreate ( savedInstanceState );
        setContentView ( R.layout.login );
        checkBox = ( CheckBox ) findViewById ( R.id.cb );

        dialog = new ProgressDialog ( this );
        dialog.setMessage ( "加载中..." );
        if ( UserFileDeal.isExists ( this ) ) {
            if ( SharedPreferencesHelper.isCookieExists ( this ) ) {
                String cookie = SharedPreferencesHelper.getCookie ( this );
                if ( ! CookieTools.hasExpired ( cookie ) ) {
                    if ( ! dialog.isShowing () ) {
                        dialog.show ();
                    }
                    MyConstants.MyCookie = cookie;
                    VolleyCookieBase.volleyGet ( MyConstants.TIME, TimeModel.class, cookie, timeHandler );
                }
            }
        }

    }


    public void btn_OK_click ( View v ) {
        struser = ( ( TextView ) findViewById ( R.id.userno ) ).getText ().toString ();
        strpwd = ( ( TextView ) findViewById ( R.id.userpwd ) ).getText ().toString ();
        //判断用户名是否为空
        if ( struser == null || struser.toString ().equals ( "" ) ) {
            DialogDemo.builder ( Login.this, "错误信息", "用户名不能为空！" );
            return;
        }
        //判断密码是否为空
        else if ( strpwd == null || strpwd.toString ().equals ( "" ) ) {
            DialogDemo.builder ( Login.this, "错误信息", "密码不能为空！" );
            return;
        }

        LoginModel loginModel = new LoginModel ();
        loginModel.setEmail ( struser );
        loginModel.setPassword ( strpwd );
        if ( ! dialog.isShowing () ) {
            dialog.show ();
        }
        loginRequest = VolleyBase.volleyPost ( MyConstants.LOGIN, loginModel, UserModel.class, getWebHandler () );
    }

    @Override
    public void webConSuccessed ( Object obj ) {
        if ( obj instanceof UserModel ) {
            UserModel userModel = ( UserModel ) obj;
            if ( loginRequest instanceof JsonRequest ) {
                JsonRequest jsonRequest = ( JsonRequest ) loginRequest;
                String cookie = jsonRequest.getGetCookie ();

                Log.i ( "MyCookie", "cookie:" + cookie );
                if ( cookie != null ) {
                    SharedPreferencesHelper.setCookie ( getContext (), cookie );
                    MyConstants.MyCookie = cookie;
                }
                if ( checkBox.isChecked () ) {
                    userModel.setCookie ( cookie );
                    UserFileDeal.saveUser ( this , userModel );
                }

                VolleyCookieBase.volleyGet ( MyConstants.TIME, TimeModel.class, cookie, timeHandler );

            }
        }

    }

    Handler timeHandler = new Handler () {

        @Override
        public void handleMessage ( Message msg ) {
            super.handleMessage ( msg );
            switch ( msg.what ) {
                case VolleyBase.SUCCESS:
                    if ( msg.obj instanceof TimeModel ) {
                        TimeModel time = ( TimeModel ) msg.obj;
                        if ( dialog != null ) {
                            if ( dialog.isShowing () ) {
                                dialog.dismiss ();
                            }
                        }
                        DateTime dateTime = new DateTime ( time.getTime () );
                        Date date = dateTime.toDate ();
                        long maxAge = ( ( date.getTime () - System.currentTimeMillis () ) / 1000 );
                        //save
                        SharedPreferencesHelper.setMaxAge ( getContext (), maxAge );

                        Intent intent = new Intent ();
                        intent.setClass ( Login.this, MainFrm.class );
                        startActivity ( intent );
                        Login.this.finish ();

                    }
                    break;
                case VolleyBase.FAILD:
                    if ( msg.obj instanceof VolleyError ) {
                        VolleyError error = ( VolleyError ) msg.obj;
                        if ( dialog != null ) {
                            if ( dialog.isShowing () ) {
                                dialog.dismiss ();
                            }
                        }
                        if ( error.networkResponse != null ) {
                            if ( error.networkResponse.statusCode == 401 ) {
                                break;
                            }
                        } else {
                            if ( SharedPreferencesHelper.isCookieExists ( getContext () ) ) {
                                String cookie = SharedPreferencesHelper.getCookie ( getContext () );
                                if ( ! CookieTools.hasExpired ( cookie ) ) {

                                    Intent intent = new Intent ();
                                    intent.setClass ( Login.this, MainFrm.class );
                                    startActivity ( intent );
                                    Login.this.finish ();
                                } else {
                                    break;
                                }
                            }
                        }
                    }
                    break;
            }
        }
    };

    @Override
    public void webConFailed ( Object obj ) {
        if ( dialog.isShowing () ) {
            dialog.dismiss ();
        }
        if ( obj instanceof VolleyError ) {
            VolleyError error = ( VolleyError ) obj;
            if ( error.networkResponse != null ) {
                if ( error.networkResponse.data != null ) {
                    String faileValue = new String ( error.networkResponse.data );
                    Gson gson = new Gson ();
                    MessageModel message = gson.fromJson ( faileValue, MessageModel.class );
                    Log.i ( "FailedValue", "value:" + message.getMsg () );
                    Toast.makeText ( getContext (), message.getMsg (), Toast.LENGTH_SHORT ).show ();
                }
            }
        }
    }

    @Override
    public void webConWaitting ( int process ) {

    }
}